﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using Emgu.CV;
using Emgu.CV.Structure;

namespace Domotica.Gazing
{
    class FaceRecognizer
    {
        private static readonly HaarCascade HaarFace;
        private static readonly HaarCascade HaarEye;

        static FaceRecognizer()
        {
            //Read the HaarCascade objects
            HaarFace = new HaarCascade("Recognition\\haarcascade_frontalface_alt_tree.xml");
            HaarEye = new HaarCascade("Recognition\\haarcascade_eye.xml");

        }

        public static FaceList FindFaces(Image<Gray, Byte> gray)
        {
            FaceList faces = new FaceList();

            //Detect the faces  from the gray scale image and store the locations as rectangle
            //The first dimensional is the channel
            //The second dimension is the index of the rectangle in the specific channel
            MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(HaarFace, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));

            foreach (MCvAvgComp f in facesDetected[0])
            {
                Face face = new Face(f.rect);
                faces.Add(face);
                //Set the region of interest on the faces
                gray.ROI = f.rect;
                MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(HaarEye, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
                gray.ROI = Rectangle.Empty;

                int h02 = (f.rect.Height * 2) / 10;
                int w2 = f.rect.Width/2;
                Rectangle rightFace = new Rectangle(f.rect.X, f.rect.Y + h02, w2, h02 * 2);
                Rectangle leftFace = new Rectangle(f.rect.X + w2, f.rect.Y + h02, w2, h02 * 2);

                foreach (MCvAvgComp e in eyesDetected[0])
                {
                    Rectangle r = e.rect;
                    Rectangle r2 = new Rectangle(r.X + f.rect.X, r.Y + f.rect.Y, r.Width, r.Height);
                    EyePosition position = EyePosition.Unknown;
                    if (rightFace.Contains(r2))
                    {
                        position = EyePosition.Right;
                    }
                    else if (leftFace.Contains(r2))
                    {
                        position = EyePosition.Left;
                    }
                    Eye eye = new Eye(r2, position);
                    face.Eyes.Add(eye);
                }
            }
            return faces;
        }
    }
}
